<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { ElButton, ElLoading } from 'element-plus'

import { Table } from '@/components/Table'
import { dbGoodsListApi, dbGoodsexportApi } from '@/api/forms'
import { ucOrgListApi } from '@/api/uc/org'
import { ucUserListAdminApi } from '@/api/uc/user'
import { adminCsClassListApi } from '@/api/cs/class'
import { useTable } from '@/hooks/web/useTableTest'
import { TableData } from '@/api/cs/goods/types'
import { ref, reactive, watch } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: TableData[]
  },
  any
>({
  getListApi: dbGoodsListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { setSearchParams } = methods

// 所属分类
const newClassData = ref<any[]>([])
const getClassList = async () => {
  // const loadingInstance = ElLoading.service(options)
  const loadingMain = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await adminCsClassListApi({})
    .catch(() => {})
    .finally(() => {
      setTimeout(() => {
        loadingMain.close()
      }, 500)
    })
  if (res) {
    newClassData.value = [{ class_id: '0', class_name: ' ' }, ...res.data]
  }
}
getClassList()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'goods_id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  // {
  //   field: 'pasture_org_id',
  //   label: '所属牧场',
  //   width: 150,
  //   search: {
  //     component: 'DialogRefer',
  //     componentProps: {
  //       getListApi: zcPastureListAdminApi,
  //       response: { count: 'count', data: 'data' },
  //       title: '选择创建人（双击选择）',
  //       nameField: 'pasture_org_name',
  //       relNameField: 'org_name',
  //       valueField: 'org_id',
  //       crudSchemas: [
  //         { field: 'org_name', label: '牧场名称', search: { show: true } }
  //         // { field: 'org_id', label: '牧场ID', search: { show: true } }
  //       ]
  //     },
  //     show: true
  //   },
  //   table: {
  //     show: false
  //   }
  // },
  {
    field: 'org_id',
    label: '所属组织',
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: ucOrgListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择组织（双击选择）',
        nameField: 'org_name',
        valueField: 'org_id',
        crudSchemas: [
          {
            field: 'org_name',
            label: '组织名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    form: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: ucOrgListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择组织（双击选择）',
        nameField: 'org_name',
        valueField: 'org_id',
        crudSchemas: [
          {
            field: 'org_name',
            label: '组织名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'org_name',
    label: '所属组织',
    width: 150,
    form: {
      show: false
    }
  },
  {
    field: 'goods_name',
    label: '商品名称',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'goods_sn',
    label: '商品编号',
    width: 180,
    search: {
      show: true
    }
  },
  {
    field: 'is_up_shelf',
    label: '是否上架',
    width: 100,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('is', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.is
      },
      show: true
    }
  },
  {
    field: 'user_id',
    label: '创建人',
    form: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: ucUserListAdminApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择创建人（双击选择）',
        nameField: 'user_name',
        relNameField: 'nickname',
        valueField: 'user_id',
        crudSchemas: [
          {
            field: 'nickname',
            label: '姓名',
            search: {
              show: true
            }
          },
          {
            field: 'username',
            label: '用户名',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'user_name',
    label: '创建人',
    form: {
      show: false
    }
  },
  {
    field: 'class_id',
    label: '所属分类',
    width: 120,
    search: {
      component: 'TreeSelect',
      componentProps: {
        data: newClassData,
        'check-strictly': true,
        'default-expand-all': true,
        'node-key': 'class_id',
        props: {
          children: 'children',
          label: 'class_name'
        }
      },
      show: true
    },
    form: {
      component: 'TreeSelect',
      componentProps: {
        data: newClassData,
        'check-strictly': true,
        'default-expand-all': true,
        'node-key': 'class_id',
        props: {
          children: 'children',
          label: 'class_name'
        }
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },

  {
    field: 'class_name',
    label: '所属分类',
    width: 120,
    form: {
      show: false
    }
  },
  {
    field: 'goods_price',
    label: '商品价格',
    width: 120,
    form: {
      component: 'InputNumber',
      componentProps: {
        precision: 2,
        step: 0.01,
        mix: 0
      },
      show: true
    }
  },
  {
    field: 'goods_thumbnail',
    label: '缩略图URL',
    table: {
      show: false
    },
    form: {
      component: 'Upload'
    },
    detail: {
      span: 24,
      show: true
    }
  },
  // {
  //   field: 'sku_list',
  //   label: '规格列表',
  //   table: {
  //     show: false
  //   },
  //   form: {
  //     componentProps: {
  //       type: 'textarea'
  //     },
  //     colProps: {
  //       span: 24
  //     }
  //   },
  //   detail: {
  //     span: 24,
  //     show: true
  //   }
  // },
  {
    field: 'goods_describe',
    label: '商品描述',
    width: 120,
    form: {
      componentProps: {
        type: 'textarea'
      },
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const exportClick = async () => {
  dialogTableVisible.value = true
  let aaa: any = tableObject.paramsObj.params
  console.log(aaa)
  let { data }: any = await dbGoodsexportApi({
    class_id: aaa.class_id,
    goods_name: aaa.goods_name,
    is_up_shelf: aaa.is_up_shelf,
    goods_sn: aaa.goods_sn,
    org_id: aaa.org_id
  })
    .catch(() => {})
    .finally(() => {
      // saveLoading.value = false
    })
  if (data) {
    // window.open(data.url)

    console.log(data.count, Math.ceil(data.count / 10000))
    FormsNumber.value = Math.ceil(data.count / 10000)
  }
  // ElMessage.warning('开发中，稍后查看')
}

const FormsNumber = ref(0)
const dialogTableVisible = ref(false)

const Export = async (index) => {
  let aaa: any = tableObject.paramsObj.params
  console.log(aaa)
  let { data }: any = await dbGoodsexportApi({
    class_id: aaa.class_id,
    goods_name: aaa.goods_name,
    is_up_shelf: aaa.is_up_shelf,
    goods_sn: aaa.goods_sn,
    org_id: aaa.org_id,
    pageNo: index,
    pageSize: 10000
  })
    .catch(() => {})
    .finally(() => {
      // saveLoading.value = false
    })
  if (data) {
    window.open(data.url)

    console.log(data, Math.ceil(data.count / 10000))
    // FormsNumber.value = Math.ceil(data.count / 10000)
  }
}

const newFixedSearch = ref({})
watch(
  () => wsCache.get('userInfo'),
  (val: any) => {
    if (!val) return
    // 设置固定条件
    newFixedSearch.value = {
      is_die: '0',
      org_id: val.default_org_id
    }
    tableObject.fixedSearch = newFixedSearch.value
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<template>
  <ContentWrap>
    <!-- <Sku /> -->
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px w-[100%] flex justify-end" v-show="tableObject.paramsObj.params">
      <ElButton type="primary" @click="exportClick()"> 导出EXCEL </ElButton>
    </div>
    <Table
      v-show="tableObject.paramsObj.params"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    />
  </ContentWrap>

  <el-dialog v-model="dialogTableVisible" title="商品主档导出详情">
    <div style="margin: 20px" v-for="(item, index) in FormsNumber" :key="index">
      <span style="margin: 20px">商品主档 - {{ item }}</span>
      <ElButton type="primary" @click="Export(item)">导出</ElButton>
    </div>
  </el-dialog>
</template>
